package UI.Main;


import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.math.RoundingMode;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DecimalFormat;

/**
 * @author 杨明政
 * @version  2021.0601
 * @since 1.8
 */

/**
 * 文件接受端类.
 * For example:
 * <pre>
 * FileTransferServer ser = new FileTransferServer(port);
 * ser.load();
 * </pre>
 * @author 杨明政
 * @see java.net.ServerSocket
 */

public class FileTransferServer extends ServerSocket {

    private static int SERVER_PORT;

    private static DecimalFormat df = null;

    static {
        df = new DecimalFormat("#0.0");
        df.setRoundingMode(RoundingMode.HALF_UP);
        df.setMinimumFractionDigits(1);
        df.setMaximumFractionDigits(1);
    }
    /**
     * 构造函数
     * 与程序接收端建立连接
     * @param port 接收端端口号
     * @throws Exception 连接异常
     */
    public FileTransferServer(int port) throws Exception {
        super(port);
    }
    /**
     * 接收文件内容
     * @throws Exception 接收异常
     */
    public void load() throws Exception {
        while (UserPage.serverFlag) {
            Socket socket = this.accept();
            Thread a=new Thread(new Task(socket));
            a.start();
        }
    }

    /**
     * 接受任务类.
     * @author 杨明政
     * @see java.lang.Runnable
     */
    class Task implements Runnable {

        private Socket socket;

        private DataInputStream dis;

        private FileOutputStream fos;

        public Task(Socket socket) {
            this.socket = socket;
        }


        @Override
        public void run() {
            try {
                dis = new DataInputStream(socket.getInputStream());
                String fileName = dis.readUTF();
                long fileLength = dis.readLong();
                File directory = new File("./receive files");
                if(!directory.exists()) {
                    directory.mkdir();
                }
                File file = new File(directory.getAbsolutePath() + File.separatorChar + fileName);
                fos = new FileOutputStream(file);

                byte[] bytes = new byte[1024];
                int length = 0;
                while((length = dis.read(bytes, 0, bytes.length)) != -1) {
                    fos.write(bytes, 0, length);
                    fos.flush();
                }
                System.out.println("[File Name" + fileName + "] [Size" + getFormatFileSize(fileLength) + "] ========");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if(fos != null)
                        fos.close();
                    if(dis != null)
                        dis.close();
                    socket.close();
                } catch (Exception e) {}
            }
        }
    }

    /**
     * 获取传输文件大小
     * @param length 传输文件字节数
     * @return 文件大小
     */
    private String getFormatFileSize(long length) {
        double size = ((double) length) / (1 << 30);
        if(size >= 1) {
            return df.format(size) + "GB";
        }
        size = ((double) length) / (1 << 20);
        if(size >= 1) {
            return df.format(size) + "MB";
        }
        size = ((double) length) / (1 << 10);
        if(size >= 1) {
            return df.format(size) + "KB";
        }
        return length + "B";
    }

}
